<template>
  <div class="symptom-second-view">

    <!-- 全局加载组件 -->
    <LoadingOverlay />
    
    <div class="symptom-second-container">
      <div class="health-status-area" v-if="free_nums > 0" >
        <div class="status-block free-count">
          <span class="status-icon">🎁</span>
          <span class="status-text">{{ t('you_have') }} {{ free_nums }} {{ t('free_consultation_opportunities') }}</span>
        </div>
      </div>
      <div v-else-if="symptom_inquiry_once_mums > 0 && !free_nums" class="health-status-area">
        <div class="status-block usage-count">
          <span class="status-icon">🎁</span>
          <span class="status-text">{{ t('your_once_card_still_has') }} {{ symptom_inquiry_once_mums }} {{
            t('usage_opportunities') }}</span>
        </div>
      </div>
      <!-- 已选症状区域 -->
      <div class="selected-symptoms-section">
        <h3 class="section-title">{{ t('selected_symptoms') }}</h3>
        <div class="symptoms-list">
          <div class="symptom-tag" v-for="(symptom, index) in displayedSymptomNames" :key="index">
            {{ symptom }}
          </div>
        </div>
      </div>
      
      <!-- 性别年龄区域 -->
      <div class="user-info-section">
        <h3 class="section-title">{{ t('basic_info') }}</h3>
        <div class="user-info-content">
          <div class="info-item">
            <span class="info-label">{{ t('gender') }}：</span>
            <div class="gender-options">
              <div 
                class="gender-option" 
                :class="{ active: gender === '男' }" 
                @click="gender = '男'"
              >{{ t('male') }}</div>
              <div 
                class="gender-option" 
                :class="{ active: gender === '女' }" 
                @click="gender = '女'"
              >{{ t('female') }}</div>
            </div>
          </div>
          
          <div class="info-item">
            <span class="info-label">{{ t('age') }}：</span>
            <el-input-number 
              v-model="age" 
              :min="1" 
              :max="120" 
              size="small"
              class="age-input"
            ></el-input-number>
            <span class="age-unit">{{ t('age_unit') }}</span>
          </div>
        </div>
      </div>
      
      <!-- 舌像上传区域 -->
      <div class="tongue-image-section">
        <h3 class="section-title">{{ t('tongue_image_upload') }}</h3>
        <div class="upload-area">
          <el-upload
            class="tongue-uploader"
            :show-file-list="false"
            :before-upload="beforeTongueImageUpload"
            :on-success="handleTongueUploadSuccess"
            :on-error="handleTongueUploadError"
            action="#"
            :http-request="uploadTongueImage"
          >
            <img v-if="tongueImageUrl" :src="tongueImageUrl" class="tongue-image" />
            <div v-else class="upload-placeholder">
              <i class="el-icon-plus upload-icon"></i>
              <div class="upload-text">{{ t('click_to_upload_tongue_photo') }}</div>
            </div>
          </el-upload>
          <div class="upload-tip" v-if="!tongueImageUrl">{{ t('upload_tip') }}</div>
        </div>
      </div>
      
      <!-- 查询结果区域 -->
      <div v-if="showResult" class="symptom-result-section">
        <h3 class="section-title">{{ t('query_result') }}</h3>
        <div class="result-content">
          <!-- 使用共通化的打字机效果组件 -->
          <TypewriterText 
            :parsedResult="parsedResult"
            :displayedText="displayedText"
            :currentSection="currentSection"
            :currentElement="currentElement"
            :isTyping="isTyping"
            :showResult="showResult"
          />
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button class="back-btn" @click="goBack">{{ t('back') }}</button>
        
        <button v-if="free_nums || (!free_nums && !symptom_inquiry_once_mums)" class="query-btn" @click="handleQueryClick">{{ hasFreeQueries ? t('query') : t('pay_to_detect') }}</button>
        <button v-else class="query-btn" @click="directSubmitSymptomQuery">{{ t('query') }}</button>
      </div>

      <!-- 直接查询 -->
      
      
      <!-- 支付对话框组件 -->
      <PaymentDialog 
        ref="paymentDialog" 
        :packageInfo="currentPackage" 
        @success="handlePaymentSuccess" 
        @cancel="handlePaymentCancel" 
        @error="handlePaymentError" 
      />
    </div>
    
    <!-- 结果弹窗 -->
    <el-dialog
      v-model="isModalVisible"
      :title="t('diagnosis_result')"
      width="80%"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <div class="result-content">
        <pre class="result-text">{{ symptomText }}</pre>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hideModal">{{ t('close') }}</el-button>
          <el-button type="primary" @click="saveResult">{{ t('save_result') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { submitSymptomQuery } from '@/api/symptom';
import { getUserCombo } from '@/api/chat';
import { useLoadingStore } from '@/store/loadingStore';
import { useTypewriter } from '@/hooks/useTypewriter';
import PaymentDialog from '@/components/common/PaymentDialog.vue';
import TypewriterText from '@/components/common/TypewriterText.vue';
import LoadingOverlay from '@/components/common/LoadingOverlay.vue';
import { useLanguageStore } from '@/store/languageStore';
import useLogin from '@/hooks/useLogin';
import { useUserStore } from '@/store/userStore';

// 根据分类ID获取类型
const userStore = useUserStore();
const { toogleLoginModal } = useLogin()
const { t } = useLanguageStore();

// 初始化路由
const router = useRouter();

// 定义组件名称
defineOptions({
  name: 'SymptomSecond'
});

// 使用加载状态store
const loadingStore = useLoadingStore();

const free_nums = ref(0);
// 已选症状
const selectedSymptoms = ref([]);
const selectedSymptomIds = ref([]);
const selectedSymptomData = ref([]); // 包含多语言字段的症状数据

// 使用打字机效果hook
const {
  parsedResult,
  displayedText,
  currentSection,
  currentElement,
  isTyping,
  showResult,
  setResultData,
  startTypingEffect,
  resetTypewriter
} = useTypewriter();

// 性别与年龄
const gender = ref('男');
const age = ref(30);

// 舌像上传
const tongueImageUrl = ref('');
const tongueImageFile = ref(null);

// 结果弹窗相关
const isModalVisible = ref(false);
const symptomText = ref('');

// 支付相关
const paymentDialog = ref(null);
const hasFreeQueries = ref(false);
const currentPackage = ref({
  type: 'symptom_inquiry_once_mums',
  name: '症状检测次卡',
  price: 99 // 默认价格
});

const symptom_inquiry_once_mums = ref(0);

// 根据当前语言显示症状名称
const displayedSymptomNames = computed(() => {
  const { getCurrentLang } = useLanguageStore();
  const currentLang = getCurrentLang || 'zh-cn';

  // 语言代码映射到字段后缀
  const langFieldMap = {
    'zh-cn': 'zh_cn',
    'en-us': 'en_us',
    'ja-jp': 'ja_jp',
    'be-by': 'be_by'
  };
  const fieldSuffix = langFieldMap[currentLang] || 'zh_cn';

  return selectedSymptomData.value.map(symptom => {
    return symptom[`name_${fieldSuffix}`] || symptom.name_zh_cn || symptom.name || '';
  });
});

// 获取本地存储的症状数据
const getSelectedSymptoms = () => {
  try {
    const storedIds = localStorage.getItem('chooseTxt');
    const storedSymptomData = localStorage.getItem('selectedSymptomData');

    if (storedIds && storedSymptomData && typeof storedIds === 'string' && typeof storedSymptomData === 'string') {
      selectedSymptomIds.value = JSON.parse(storedIds);
      selectedSymptomData.value = JSON.parse(storedSymptomData);

      // 为了兼容性，同时设置旧的格式
      selectedSymptoms.value = selectedSymptomData.value.map(symptom => symptom.name_zh_cn || symptom.name || '');
    } else {
      // 兼容旧版本的存储格式
      const storedNames = localStorage.getItem('chooseTxtContent');
      if (storedIds && storedNames && typeof storedIds === 'string' && typeof storedNames === 'string') {
        selectedSymptomIds.value = JSON.parse(storedIds);
        selectedSymptoms.value = JSON.parse(storedNames);
        // 创建兼容的症状数据格式
        selectedSymptomData.value = selectedSymptomIds.value.map((id, index) => ({
          value: id,
          name_zh_cn: selectedSymptoms.value[index] || '',
          name_en_us: selectedSymptoms.value[index] || '',
          name_ja_jp: selectedSymptoms.value[index] || '',
          name_be_by: selectedSymptoms.value[index] || ''
        }));
      } else {
        ElMessage.warning('未找到选择的症状数据，请返回重新选择');
        router.push('/symptom');
      }
    }
  } catch (error) {
    console.error('获取本地存储症状数据失败:', error);
    ElMessage.error('获取症状数据失败');
    router.push('/symptom');
  }
};

watch(() => userStore.isLoggedIn, () => {
  if (userStore.isLoggedIn) {
    getUserCardInfo();
  }
})

// 获取症状详情数据
// const fetchSymptomDetails = async () => {
//   if (selectedSymptomIds.value.length === 0) {
//     return;
//   }
  
//   try {
//     isLoading.value = true;
//     loadingStore.startLoading('正在加载症状详情...');
    
//     // 这里可以根据实际API调整，暂时模拟一些数据
//     // 实际应用中可能需要调用API获取详情
//     setTimeout(() => {
//       symptomDetails.value = selectedSymptoms.value.map(name => ({
//         title: name,
//         description: `这是关于"${name}"的详细描述信息。在实际应用中，这里会显示从服务器获取的详细信息。`
//       }));
      
//       isLoading.value = false;
//       loadingStore.endLoading();
//     }, 1000);
    
//   } catch (error) {
//     console.error('获取症状详情失败:', error);
//     ElMessage.error('获取症状详情失败');
//     isLoading.value = false;
//     loadingStore.endLoading();
//   }
// };

// 舌像上传前的验证
const beforeTongueImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  
  tongueImageFile.value = file;
  return true;
};

// 自定义上传方法
const uploadTongueImage = (options) => {
  const { file } = options;
  
  // 创建一个临时的URL以预览图片
  tongueImageUrl.value = URL.createObjectURL(file);
  
  // 这里可以添加实际的上传逻辑，例如：
  // const formData = new FormData();
  // formData.append('tongueImage', file);
  // 发送到服务器...
  
  // 模拟上传成功
  setTimeout(() => {
    options.onSuccess();
  }, 500);
};

// 上传成功处理
const handleTongueUploadSuccess = () => {
  ElMessage.success('舌像上传成功');
};

// 上传失败处理
const handleTongueUploadError = () => {
  ElMessage.error('舌像上传失败，请重试');
  tongueImageUrl.value = '';
  tongueImageFile.value = null;
};

// 返回上一页
const goBack = () => {
  router.push('/symptom');
};

// 根据当前语言获取对应的汤药名称或成分
const getFormulaByLanguage = (formulaData, field = 'name') => {
  const { getCurrentLang } = useLanguageStore();
  const currentLang = getCurrentLang || 'zh-cn';

  // 语言代码映射到字段后缀
  const langFieldMap = {
    'zh-cn': 'zh_cn',
    'en-us': 'en_us',
    'ja-jp': 'ja_jp',
    'be-by': 'be_by'
  };
  const fieldSuffix = langFieldMap[currentLang] || 'zh_cn';

  return formulaData[`${field}_${fieldSuffix}`] || formulaData[`${field}_zh_cn`] || '';
};

// 显示结果弹窗 - 参考小程序的showModal方法
const showModal = async () => {
  const isLoggedIn = toogleLoginModal();
  if (!isLoggedIn) return;
  if (selectedSymptoms.value.length === 0) {
    ElMessage.warning('请至少选择1个症状');
    return;
  }
  
  if (!gender.value) {
    ElMessage.warning('请选择性别');
    return;
  }
  
  if (!age.value || age.value < 1) {
    ElMessage.warning('请输入有效年龄');
    return;
  }
  
  try {
    loadingStore.startLoading('正在提交查询...');
    
    // 参考小程序的数据格式
    const response = await submitSymptomQuery({
      // 'symptom_desc': selectedSymptoms.value.join(','),
      'symptom_desc': selectedSymptomIds.value.join(','),
      // 'gender': gender.value,
      // 'age': age.value,
      // 'has_tongue_image': tongueImageUrl.value ? 1 : 0
    });
    
    // 关闭加载状态
    loadingStore.endLoading();
    
    if (response.code === 0) {
      // 重置打字机效果
      resetTypewriter();
      
      // 构建结果数据结构，用于打字机效果
      const resultData = [];
      const isEmpty = (obj) => {
        return Object.keys(obj).length === 0;
      };
      
      if (!isEmpty(response.data)) {
        // 创建一个包含所有药方的部分
        const prescriptionSection = {
          title: '推荐药方',
          paragraphs: []
        };
        
        // 将每个药方添加为段落
        Object.keys(response.data).forEach(key => {
          // 后端现在返回的格式：key => {name_zh_cn, name_en_us, ..., ingredients_zh_cn, ...}
          const formulaData = response.data[key];

          // 获取当前语言的汤药名称和成分
          const formulaName = getFormulaByLanguage(formulaData, 'name');
          const ingredients = getFormulaByLanguage(formulaData, 'ingredients');

          // 格式化显示
          let displayText = `${t('formula_name')}: ${formulaName}`;
          if (ingredients) {
            displayText += `\n${t('ingredients')}: ${ingredients}`;
          }

          prescriptionSection.paragraphs.push(displayText);
        });
        
        resultData.push(prescriptionSection);
      } else {
        // 如果没有数据，添加一个空结果部分
        resultData.push({
          title: '查询结果',
          paragraphs: ['暂无药方']
        });
      }
      
      // 设置结果数据并开始打字机效果
      setResultData(resultData);
      startTypingEffect(50, 30);
      
      // 保存原始文本用于弹窗显示
      // let respSymptomText = '';
      // if (!isEmpty(response.data)) {
      //   Object.keys(response.data).forEach(key => {
      //     respSymptomText += key + ' : ' + response.data[key].join(',') + '\n';
      //   });
      // }
      // symptomText.value = respSymptomText.length === 0 ? '暂无药方' : respSymptomText;
      
      // 显示结果区域
      showResult.value = true;
      
      // 清空之前选择的症状（可选，根据业务需求决定）
      // localStorage.removeItem('chooseTxt');
      // localStorage.removeItem('chooseTxtContent');
    } else {
      throw new Error(response.msg || '查询失败');
    }
    
    loadingStore.endLoading();
  } catch (error) {
    console.error('提交查询失败:', error);
    ElMessage.error('提交查询失败');
    loadingStore.endLoading();
  }
};

// 隐藏结果弹窗
const hideModal = () => {
  isModalVisible.value = false;
};



// 保存结果
const saveResult = () => {
  // 这里可以添加保存结果的逻辑
  ElMessage.success('结果已保存');
  hideModal();
};

// 获取用户资费卡信息
const getUserCardInfo = async () => {
  try {
    const response = await getUserCombo();
    if (response.code === 0) {
      // 检查是否有免费次数
      hasFreeQueries.value = response.data.free_nums > 0;
      free_nums.value = response.data.free_nums;
      // 如果有套餐价格信息，可以更新默认价格
      if (response.data.zhongyao_once_nums) {
        currentPackage.value.price = response.data.zhongyao_once_nums;
      }
      symptom_inquiry_once_mums.value = response.data.symptom_inquiry_once_mums;
    } else {
      console.error('获取资费卡信息失败:', response.msg);
    }
  } catch (error) {
    console.error('获取资费卡信息出错:', error);
  }
};

// 处理点击查询按钮
const handleQueryClick = async () => {
  const isLoggedIn = toogleLoginModal();
  if (!isLoggedIn) return;
  if (hasFreeQueries.value) {
    // 有免费次数，延迟5秒后查询
    loadingStore.startLoading('loading...');
    
    // 延迟5秒执行后续操作
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    showModal();
    getUserCardInfo();
  } else {
    // 无免费次数，打开支付弹窗
    paymentDialog.value.showPayment();
  }
};

const directSubmitSymptomQuery = async () => {
    await showModal(); // 支付成功后执行查询
    await getUserCardInfo(); // 刷新用户资费卡信息
}

// 支付成功回调
const handlePaymentSuccess = async () => {
  ElMessage.success('支付成功');
  await getUserCardInfo(); // 刷新用户资费卡信息
  showModal(); // 支付成功后执行查询
};

// 支付取消回调
const handlePaymentCancel = () => {
  ElMessage.info('支付已取消');
};

// 支付错误回调
const handlePaymentError = (error) => {
  ElMessage.error('支付失败: ' + (error?.message || '未知错误'));
};

onMounted(() => {
  getSelectedSymptoms();
  // fetchSymptomDetails();
  getUserCardInfo(); // 获取用户资费卡信息
});
</script>

<style scoped>
/* 状态显示区域样式 */
.health-status-area {
  margin: 20px 0;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
}
.free-count {
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 6px;
}
.symptom-second-view {
  min-height: 100vh;
  background-color: #f5f7ff;
  padding: 20px;
}

.symptom-second-container {
  margin-top: 20px;
  flex: 1;
  padding: 20px;
  max-width: 850px;
  margin: 60px auto 30px;
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  outline: none;
  border: none;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  position: relative;
  padding-left: 12px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background: linear-gradient(to bottom, #4a7eff, #6e9dff);
  border-radius: 2px;
}

.selected-symptoms-section,
.symptom-details-section,
.user-info-section,
.tongue-image-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.symptoms-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.symptom-tag {
  background: #f0f5ff;
  color: #4a7eff;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
}

/* 性别与年龄样式 */
.user-info-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  width: 60px;
  font-size: 15px;
  color: #333;
}

.gender-options {
  display: flex;
  gap: 15px;
}

.gender-option {
  width: 60px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.gender-option.active {
  background-color: #4a7eff;
  color: white;
  border-color: #4a7eff;
}

.age-input {
  width: 100px;
}

.age-unit {
  margin-left: 5px;
  color: #333;
}

/* 舌像上传样式 */
.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tongue-uploader {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tongue-uploader:hover {
  border-color: #4a7eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  color: #666;
  font-size: 14px;
}

.tongue-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  text-align: center;
  max-width: 200px;
}

.details-content {
  min-height: 200px;
}

.loading-placeholder,
.no-data {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.detail-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.detail-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.detail-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.back-btn,
.query-btn {
  flex: 1;
  height: 44px;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn {
  background-color: #f0f0f0;
  color: #666;
  margin-right: 10px;
}

.query-btn {
  background: linear-gradient(to right, #4a7eff, #6e9dff);
  color: white;
  margin-left: 10px;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.query-btn:hover {
  opacity: 0.9;
}

/* 结果弹窗样式 */
.result-content {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}

.result-text {
  white-space: pre-wrap;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
